package Day11.homework;

import java.util.Random;
import java.util.concurrent.locks.ReentrantReadWriteLock;

//银行账户余额查询与转账,使用ReentrantReadWriteLock实现银行账户系统
//支持并发余额查询但互斥转账操作
// (提示: 提供三个方法 查询(读锁)  存款(写锁)  取款(写锁))
public class Bank {
    double balance;
    ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    public void show(){
        try {
            String name = Thread.currentThread().getName();
            rwLock.readLock().lock();
            System.out.println(name+"查询账户余额,用时1s");
            Thread.sleep(1000);
            System.out.println(name+"当前余额："+balance);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rwLock.readLock().unlock();
        }
    }
    public void input(int money){
        try {
            String name = Thread.currentThread().getName();
            rwLock.writeLock().lock();
            System.out.println(name+"正在存储金额:"+money+",存储时长1s...");
            balance+=money;
            Thread.sleep(1000);
            System.out.println(name+"存储成功! 当前余额:"+balance);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rwLock.writeLock().unlock();
        }
    }
    public void output(int money){
        try {
            rwLock.writeLock().lock();
            String name = Thread.currentThread().getName();
            if (balance>=money) {
                System.out.println(name + "正在取出金额:"+money+",取款时长1s...");
                balance -= money;
                Thread.sleep(1000);
                System.out.println(name + "取款成功! 当前余额:" + balance);
            }else System.out.println(name+"当前余额不足！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rwLock.writeLock().unlock();
        }
    }

    public static void main(String[] args) {
        Bank b = new Bank();
        Random r = new Random();
        for (int i = 1; i <= 3; i++) {
            new Thread(()->{
                for (int j = 0; j < 5; j++) {
                    int flag = r.nextInt(3);
                    if (flag == 0) b.show();
                    else if (flag == 1) b.input(888);
                    else b.output(666);
                }
            },"用户"+i).start();
        }
    }
}
